<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/11/29
 * Time: 1:16 PM
 */
namespace app\purchase\model;
use think\Db;

/**
 * Class Goods
 * @package app\purchase\model
 * @OA\Schema(schema="Goods", description="商品模型", type="object",
 *   @OA\Property(property="goods_id", description="商品ID", type="integer", ),
 *   @OA\Property(property="goods_name", description="商品名称", type="string", ),
 *   @OA\Property(property="brand_id", description="品牌ID", type="integer", ),
 *   @OA\Property(property="brand", description="品牌信息", ref="#/components/schemas/Brand", ),
 *   @OA\Property(property="cate_id", description="分类ID", type="integer", ),
 *   @OA\Property(property="category", description="分类信息", ref="#/components/schemas/Category", ),
 *   @OA\Property(property="goods_images", description="商品图片", type="array", @OA\Items( type="string", ), ),
 *   @OA\Property(property="defaultImage", description="商品默认图片", type="string", ),
 *   @OA\Property(property="price", description="商品价格", type="number", ),
 *   @OA\Property(property="stock", description="商品库存", type="integer", ),
 *   @OA\Property(property="goods_desc", description="商品详情", type="string", ),
 *   @OA\Property(property="is_new", description="是否新品", type="boolean", ),
 *   @OA\Property(property="is_hot", description="是否热卖商品", type="boolean", ),
 *   @OA\Property(property="is_recommend", description="是否推荐商品", type="boolean", ),
 *   @OA\Property(property="is_promote", description="是否促销商品", type="boolean", ),
 *   @OA\Property(property="is_discount", description="是否打折商品", type="boolean", ),
 *   @OA\Property(property="skus", description="商品单品", type="array", @OA\Items(ref="#/components/schemas/GoodsSku"), ),
 *   @OA\Property(property="sku_default", description="默认单品ID", type="integer", format="int32", ),
 *   @OA\Property(property="defaultSku", description="默认单品", ref="#/components/schemas/GoodsSku", ),
 *   @OA\Property(property="specs", description="商品所有规格", type="array", @OA\Items(ref="#/components/schemas/GoodsSpec"), ),
 * )
 */
class Goods extends \ShopModel
{
    protected $table = 'sh_goods';

//    protected $type = [
//        'price' => 'float',
//    ];

    use \app\purchase\traits\Goods;

    /**
     * 单品
     */
//    public function sku()
//    {
//        return $this->belongsTo('GoodsSku', 'sku_id', 'sku_id');
//    }
//    public function levelPrice(){
//        return $this->belongsTo('GoodsLevelPrice', 'level_price_id');
//    }
//sh_goods_level_price
    public function levelprice()
    {
        return $this->belongsTo('GoodsLevelPrice', 'goods_id', 'goods_id');
    }
    public function clientprice(){
        return $this->belongsTo('GoodsClientPrice', 'goods_id', 'goods_id');
    }

    public function GoodsDb(){
        return Db::name('goods');
    }



    /**
     * 搜索(区别用户 用于订单页商品列表)
     */
    public function search($params){
        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 20;
        $where = [];
        //单个商品
        if(isset($params['goods_id'])&&!empty($params['goods_id'])){
            $where['goods.goods_id'] = $params['goods_id'];
        }


        //搜索
        if(!empty($params['query'])){
            $where['goods.goods_name | goods.goods_sn | goods.specification1_value | goods.specification2_value  | goods.specification3_value  | goods.keywords | goods.goods_code1 | goods.goods_code2 | goods.goods_code3'] = ['like','%'.$params['query'].'%'];
        }

        //商品名称
        if(!empty($params['goods_name'])){
            $where['goods.goods_name'] = $params['goods_name'];
        }
        //商品编号
        if(!empty($params['goods_sn'])){
            $where['goods.goods_sn'] = $params['goods_sn'];
        }
        //商品条码
        if(!empty($params['goods_code'])){
            $where['goods.goods_code1 | goods.goods_code2 | goods_code3'] = ['like','%'.$params['goods_code'].'%'];
        }
        //商品分类id
        if(!empty($params['cate_id'])){
            $where['goods.cate_id'] = $params['cate_id'];
        }

        //商品标签
        if(!empty($params['is_new'])){
            $where['goods.is_new'] = $params['is_new'];
        }
        if(!empty($params['is_hot'])){
            $where['goods.is_hot'] = $params['is_hot'];
        }

        $request = request();
       $params['client_id'] = $request->header('userId');
       $params['client_id']=6;
        //获取客户等级
        $ClientModel = new Client();
        $clientDb = $ClientModel->ClientDb();
        $clientData = $clientDb->where('client_id',$params['client_id'])->find();
        $where['level_id'] = $clientData['level_id'];

        $data = $this->GoodsDb()->alias('goods')
            ->join('sh_goods_level_price level','level.goods_id = goods.goods_id','right')
            ->where($where)
            ->where(  'goods.is_delete' ,0)
            ->where('goods_state',1)
            ->field('goods.goods_id,goods.is_units,goods.specification_id,goods.goods_img,goods.goods_sn,goods.goods_name,goods.specification1_name,goods.specification2_name,goods.specification3_name,goods.specification1_value,goods.specification2_value,goods.specification3_value,goods.goods_inventory')
            ->page($page,$pageSize)
            ->order('goods.add_goods_time desc')
            ->select();

        $GoodsUnitModel = new GoodsUnits();
        $GoodsUnitsDb = $GoodsUnitModel->GoodsUnitsDb();
        $GoodsUnitsModel = new Unit();
        $Units =  $GoodsUnitsModel->where('is_delete',0)->column('unit_name','unit_id');

        $level_id = $ClientModel->where('client_id',$params['client_id'])->value('level_id');
        $GoodsLevelPriceModel =  new GoodsLevelPrice();
        $GoodsLevelPriceDb = $GoodsLevelPriceModel->GoodsLevelPriceDb();
        $retData = [];
        foreach ($data as $k=>$v){
            //查询是否有指定客户可购
            //$data[$k]['specification'] = $data[$k]['specification1_name'].':'.$data[$k]['specification2_value'].','.$data[$k]['specification1_name'].':'.$data[$k]['specification2_value'].','.$data[$k]['specification3_name'].':'.$data[$k]['specification3_value'];


            $ClientGoodsPriceData = $this->getClientGoodsPrice($params['client_id'],$v['goods_id']);
            $Unit = $GoodsUnitsDb->where('goods_id',$v['goods_id'])->find();
            //判断单位是否可购
            $_d[0] = $Unit['is_use_initial_unit'];
            $_d[1]= $v['is_units'] && $Unit['is_use_extra1_unit'] ? $Unit['is_use_extra1_unit'] : 0;
            $_d[2] = $v['is_units'] && $Unit['is_use_extra2_unit'] ? $Unit['is_use_extra2_unit'] : 0;
            $data[$k]['unit']['unit1']['id'] =$Unit['initial_unit_id'];
            $data[$k]['unit']['unit1']['name'] =$Units[$Unit['initial_unit_id']];
            if($_d[1])$data[$k]['unit']['unit2']['id'] = $Unit['extra1_unit_id'];
            if($_d[1])$data[$k]['unit']['unit2']['name'] = $Units[$Unit['extra1_unit_id']];
            if($_d[2])$data[$k]['unit']['unit3']['id'] = $Unit['extra2_unit_id']                       ;
            if($_d[2])$data[$k]['unit']['unit3']['name'] = $Units[$Unit['extra2_unit_id']];
            if($ClientGoodsPriceData!=0){
                $data[$k]['unit']['unit1']['price'] =$ClientGoodsPriceData['client_price1'];
                if($_d[1]) $data[$k]['unit']['unit2']['price']=$ClientGoodsPriceData['client_price2'];
                if($_d[2]) $data[$k]['unit']['unit3']['price']=$ClientGoodsPriceData['client_price3'];

            }else{
                $GoodsLevelPrice = $GoodsLevelPriceDb->where('goods_id',$v['goods_id'])->where('level_id',$level_id)->field('level_price1,level_price2,level_price3')->find();
                if($GoodsLevelPrice){
                    $data[$k]['unit']['unit1']['price'] =$GoodsLevelPrice['level_price1'];
                    if($_d[1]) $data[$k]['unit']['unit2']['price']=$GoodsLevelPrice['level_price2'];
                    if($_d[2]) $data[$k]['unit']['unit3']['price']=$GoodsLevelPrice['level_price3'];

                }else{
                    $data[$k]['unit']['unit1']['price'] =$Unit['initial_unit_price'];
                    if($_d[1]) $data[$k]['unit']['unit2']['price']=$Unit['extra1_unit_price'];
                    if($_d[2]) $data[$k]['unit']['unit3']['price']=$Unit['extra2_unit_price'];
                }
            }
        }
        $o = 0;
        foreach ($data as  $k1=>$v1){
            foreach ($v1['unit'] as $k11=>$v11){

                $retData[$o]['goods_id'] = $v1['goods_id'];
                $retData[$o]['specification_id'] = $v1['specification_id'];
                $retData[$o]['goods_img'] = $v1['goods_img'];
                $retData[$o]['goods_sn'] = $v1['goods_sn'];
                $retData[$o]['goods_name'] = $v1['goods_name'];

                $retData[$o]['goods_inventory'] = $v1['goods_inventory'];
                $retData[$o]['specification1_name'] = $v1['specification1_name'];
                $retData[$o]['specification1_value'] = $v1['specification1_value'];
                $retData[$o]['specification2_name'] = $v1['specification2_name'];
                $retData[$o]['specification2_value'] = $v1['specification2_value'];
                $retData[$o]['specification3_name'] = $v1['specification3_name'];
                $retData[$o]['specification3_value'] = $v1['specification3_value'];
                $retData[$o]['unit_id'] = $v11['id'];
                $retData[$o]['unit_name'] = $v11['name'];
                $retData[$o]['price'] = $v11['price'];

                $str = '';
                if(!empty($v1['specification1_name'])){
                    $str .= $v1['specification1_name'].' : '.$v1['specification1_value'];
                }
                if(!empty($v1['specification2_name'])){
                    $str .= ','.$v1['specification2_name'].' : '.$v1['specification2_value'];
                }
                if(!empty($v1['specification3_name'])){
                    $str .= ','.$v1['specification3_name'].' : '.$v1['specification3_value'];
                }

                $str = !empty($str) ? '【'.$str.'】' : $str;

                $retData[$o]['show_name'] = $v1['goods_name'].' '.$str.' * 1 '.$v11['name'];
                $o++;
            }
        }
        return $retData;
    }

    public function allGoodsList($params){
        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 10;
        $where = [];
        //搜索
        if(!empty($params['query'])){
            $where['goods.goods_name'] = ['like','%'.$params['query'].'%'];
        }
        //商品分类id
        if(!empty($params['cate_id'])){
            $where['goods.cate_id'] = $params['cate_id'];
        }

        $request = request();
       $params['client_id'] = isset($params['client_id']) ? $params['client_id'] : $request->header('company');
        //获取客户等级
        $ClientModel = new Client();
        $clientDb = $ClientModel->ClientDb();
        $clientData = $clientDb->where('client_id',$params['client_id'])->find();
        $where['level_id'] = $clientData['level_id'];

        $data = $this->GoodsDb()->alias('goods')
            ->join('sh_goods_level_price level','level.goods_id = goods.goods_id','right')
            ->join('sh_category category','goods.cate_id = category.cate_id')
            ->where($where)
            ->where(  'goods.is_delete' ,0)
            ->where('goods_state',1)
            ->field('goods.goods_id,goods.is_units,category.cate_name,goods.specification_id,goods.goods_img,goods.goods_sn,goods.goods_name,goods.specification1_name,goods.specification2_name,goods.specification3_name,goods.specification1_value,goods.specification2_value,goods.specification3_value,goods.goods_inventory')
            ->page($page,$pageSize)
            ->order('goods.add_goods_time desc')
            ->select();
        $total = $this->GoodsDb()->alias('goods')
            ->join('sh_goods_level_price level','level.goods_id = goods.goods_id','right')
            ->where($where)
            ->where(  'goods.is_delete' ,0)
            ->where('goods_state',1)
            ->field('goods.goods_id')
            ->count();
        //var_dump($total);die;
        $GoodsUnitModel = new GoodsUnits();
        $GoodsUnitsDb = $GoodsUnitModel->GoodsUnitsDb();
        $GoodsUnitsModel = new Unit();
        $Units =  $GoodsUnitsModel->where('is_delete',0)->column('unit_name','unit_id');

        $level_id = $ClientModel->where('client_id',$params['client_id'])->value('level_id');
        $GoodsLevelPriceModel =  new GoodsLevelPrice();
        $GoodsLevelPriceDb = $GoodsLevelPriceModel->GoodsLevelPriceDb();
        $retData = [];
        foreach ($data as $k=>$v){
            //查询是否有指定客户可购
            //$data[$k]['specification'] = $data[$k]['specification1_name'].':'.$data[$k]['specification2_value'].','.$data[$k]['specification1_name'].':'.$data[$k]['specification2_value'].','.$data[$k]['specification3_name'].':'.$data[$k]['specification3_value'];


            $ClientGoodsPriceData = $this->getClientGoodsPrice($params['client_id'],$v['goods_id']);
            $Unit = $GoodsUnitsDb->where('goods_id',$v['goods_id'])->find();
            //判断单位是否可购
            $_d[0] = $Unit['is_use_initial_unit'];
            $_d[1]= $v['is_units'] && $Unit['is_use_extra1_unit'] ? $Unit['is_use_extra1_unit'] : 0;
            $_d[2] = $v['is_units'] && $Unit['is_use_extra2_unit'] ? $Unit['is_use_extra2_unit'] : 0;

            $data[$k]['unit_id'] =$Unit['initial_unit_id'];
            $data[$k]['unit_name'] = $Units[$Unit['initial_unit_id']];
            $data[$k]['quantity'] = 1;

            $str = '';
            if(!empty($v['specification1_name'])){
                $str .= $v['specification1_name'].' : '.$v['specification1_value'];
            }
            if(!empty($v['specification2_name'])){
                $str .= ','.$v['specification2_name'].' : '.$v['specification2_value'];
            }
            if(!empty($v['specification3_name'])){
                $str .= ','.$v['specification3_name'].' : '.$v['specification3_value'];
            }

            $str = !empty($str) ? '【'.$str.'】' : $str;

            $data[$k]['show_name'] = $data[$k]['goods_name'].' '.$str;

            if($ClientGoodsPriceData!=0){
                $data[$k]['order_num'] = $ClientGoodsPriceData['client_num'];
                $data[$k]['price'] = $ClientGoodsPriceData['client_price1'];
                $price1 = $ClientGoodsPriceData['client_price1'];
                if($_d[1])$price2=$ClientGoodsPriceData['client_price2'];
                if($_d[2])$price3=$ClientGoodsPriceData['client_price3'];
            }else{
                $GoodsLevelPrice = $GoodsLevelPriceDb->where('goods_id',$v['goods_id'])->where('level_id',$level_id)->field('level_price1,level_price2,level_price3,level_num')->find();
                $data[$k]['order_num'] = $GoodsLevelPrice['level_num'];
                if($GoodsLevelPrice){
                    $data[$k]['price'] = $GoodsLevelPrice['level_price1'];
                    $price1 = $GoodsLevelPrice['level_price1'];
                    if($_d[1])$price2=$GoodsLevelPrice['level_price2'];
                    if($_d[2])$price3=$GoodsLevelPrice['level_price3'];
                }else{
                    $data[$k]['price'] = $Unit['initial_unit_price'];
                    $price1 = $Unit['initial_unit_price'];
                    if($_d[1])$price2=$Unit['extra2_unit_price'];
                    if($_d[2])$price3=$Unit['extra3_unit_price'];
                }
            }

            $data[$k]['unit'][] = [
                'id' => $Unit['initial_unit_id'],
                'name' => $Units[$Unit['initial_unit_id']],
                'price' => $price1
            ];

            if($_d[1]){
                $data[$k]['unit'][] = [
                    'id' => $Unit['extra1_unit_id'],
                    'name' => $Units[$Unit['extra1_unit_id']],
                    'price' => $price2
                ];
            }

            if($_d[2]){
                $data[$k]['unit'][] = [
                    'id' => $Unit['extra2_unit_id'],
                    'name' => $Units[$Unit['extra2_unit_id']],
                    'price' => $price3
                ];
            }
        }
        $pager = [
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $total
        ];

        return [
            'data' => $data,
            'pager' => $pager
        ];
    }

    /**
     * 商品详情
     */
    public function info($params){

        $specification_id= $params['specification_id'];
        $goods_id=$params['goods_id'];
        $GoodsDesc = new \app\shop\model\Goodsdescribe();
        $GoodsDescDb = $GoodsDesc->GoodsdescribeDb();
        $desc = $GoodsDescDb->where('goods_id',$goods_id)->value('describe_content');
        $request = request();
        $client_id = $request->header('company');
        //$client_id=6;
        $goodsModel = new \app\shop\model\Goods();
        $GoodsDb = $goodsModel->GoodsDb();
        $GoodsLevelPrice = new GoodsLevelPrice();
        $GoodsLevelPriceDb = $GoodsLevelPrice->GoodsLevelPriceDb();
        $GoodsClientPrice = new GoodsClientPrice();
        $GoodsClientPriceDb = $GoodsClientPrice->GoodsClientPriceDb();
        $GoodsImg = new \app\shop\model\GoodsImg();
        $GoodsimgDb = $GoodsImg->GoodsimgDb();
        $GoodsAccessory = new  GoodsAccessory();
        $GoodsAccessoryDb = $GoodsAccessory->GoodsAccessoryDb();
        $specificationName = [];
        $specificationValue = [[],[],[]];
        $specificationThis = ['','',''];
        $ClientModel = new Client();
        $clientDb = $ClientModel->ClientDb();
        $clientData = $clientDb->where('client_id',$client_id)->find();
        $level_id = $clientData['level_id'];
        $specificationGoods = $GoodsDb->alias('a')
            ->join('sh_goods_level_price c','a.goods_id = c.goods_id','right')
            ->where('c.level_id',$level_id)
            ->where('a.specification_id',$specification_id)->select();
            
        if(count($specificationGoods)>0){

            $specificationName=[$specificationGoods[0]['specification1_name'],$specificationGoods[0]['specification2_name'],$specificationGoods[0]['specification3_name']];
        }
        //var_dump($specificationGoods);die;
        $rGoodsData = [];
        $goods_ids = [];
        $GoodsUnits = new GoodsUnits();
        $GoodsUnitsDb = $GoodsUnits->GoodsUnitsDb();
        $GoodsUnitsModel = new Unit();
        $Units =  $GoodsUnitsModel->where('is_delete',0)->column('unit_name','unit_id');
        foreach ($specificationGoods as $k=>$v){
            $goods_ids[] = $v['goods_id'];
            //判断单位是否可购
            $Unit = $GoodsUnitsDb->where('goods_id',$v['goods_id'])->find();
            $_d[0] = $Unit['is_use_initial_unit'];
            $_d[1]= $v['is_units'] && $Unit['is_use_extra1_unit'] ? $Unit['is_use_extra1_unit'] : 0;
            $_d[2] = $v['is_units'] && $Unit['is_use_extra2_unit'] ? $Unit['is_use_extra2_unit'] : 0;
            if($v['goods_id']==$goods_id){
                $specificationThis[0] =  $v['specification1_value'];
                $specificationThis[1] =  $v['specification2_value'];
                $specificationThis[2] =  $v['specification3_value'];
            }
           // $tK = $v['specification1_value'].'|~|'.$v['specification2_value'].'|~|'.$v['specification3_value'];
            if(!in_array($v['specification1_value'],$specificationValue[0]))$specificationValue[0][] = $v['specification1_value'];
            if(!in_array($v['specification2_value'],$specificationValue[1]))$specificationValue[1][] = $v['specification2_value'];
            if(!in_array($v['specification3_value'],$specificationValue[2]))$specificationValue[2][] = $v['specification3_value'];
            $rGoodsData[$k] = $v;
            $rGoodsData[$k]['cate_name'] = Db::name('category')->where('cate_id',$v['cate_id'])->value('cate_name');
            $rGoodsData[$k]['produced_time'] = !empty($v['produced_time'])?'':date('Y-m-d',strtotime($v['produced_time']));
            $clientPrice = $GoodsClientPriceDb->where('goods_id',$v['goods_id'])->where('client_id',$client_id)->where('client_purchase',0)->find();
            
            //获取价格
            if(!empty($clientPrice)){
                $rGoodsData[$k]['price'] = $ClientGoodsPriceData['client_price1'];
                $price1 = $ClientGoodsPriceData['client_price1'];
                if($_d[1])$price2=$ClientGoodsPriceData['client_price2'];
                if($_d[2])$price3=$ClientGoodsPriceData['client_price3'];
            }else{
                $clientLevel = $GoodsLevelPriceDb->where('goods_id',$v['goods_id'])->where('level_id',$level_id)->field('level_price1,level_price2,level_price3')->find();
                if($GoodsLevelPrice){
                    $rGoodsData[$k]['price'] = $clientLevel['level_price1'];
                    $price1 = $clientLevel['level_price1'];
                    if($_d[1])$price2=$clientLevel['level_price2'];
                    if($_d[2])$price3=$clientLevel['level_price3'];
                }else{
                    $rGoodsData[$k]['price'] = $Unit['initial_unit_price'];
                    $price1 = $Unit['initial_unit_price'];
                    if($_d[1])$price2=$Unit['extra1_unit_price'];
                    if($_d[2])$price3=$Unit['extra2_unit_price'];
                }
            }

            $rGoodsData[$k]['unit'][] = [
                'id' => $Unit['initial_unit_id'],
                'name' => $Units[$Unit['initial_unit_id']],
                'price' => $price1,
                'origin_price' => $Unit['initial_unit_price']
            ];

            if($_d[1]){
                $rGoodsData[$k]['unit'][] = [
                    'id' => $Unit['extra1_unit_id'],
                    'name' => $Units[$Unit['extra1_unit_id']].'('.$Unit['extra1_unit_ratio'].$Units[$Unit['initial_unit_id']].')',
                    'price' => $price2,
                    'origin_price' => $Unit['extra1_unit_price']
                ];
            }

            if($_d[2]){
                $rGoodsData[$k]['unit'][] = [
                    'id' => $Unit['extra2_unit_id'],
                    'name' => $Units[$Unit['extra2_unit_id']].'('.$Unit['extra2_unit_ratio'].$Units[$Unit['initial_unit_id']].')',
                    'price' => $price3,
                    'origin_price' => $Unit['extra2_unit_price']
                ];
            }

            // if(!empty($clientPrice)){
            //     $rGoodsData[$k]['price']['price1'] = $clientPrice['client_price1'];
            //     if($_d[1])$rGoodsData[$k]['price']['price2'] = $clientPrice['client_price2'];
            //     if($_d[2])$rGoodsData[$k]['price']['price3'] = $clientPrice['client_price3'];
            // }else{
            //     $clientLevel = $GoodsLevelPriceDb->where('goods_id',$v['goods_id'])->where('level_id',$level_id)->field('level_price1,level_price2,level_price3')->find();
            //     $rGoodsData[$k]['price']['price1'] = $clientLevel['level_price1'];
            //     if($_d[1])$rGoodsData[$k]['price']['price2'] = $clientLevel['level_price2'];
            //     if($_d[2]) $rGoodsData[$k]['price']['price3'] = $clientLevel['level_price3'];
            // }



            // $rGoodsData[$k]['goods_imgs'] = $GoodsimgDb->alias('a')->join('sh_img i','i.img_id=a.img_id')->where('a.goods_id',$v['goods_id'])->select();
            $rGoodsData[$k]['goods_accessory'] = $GoodsAccessoryDb->alias('b')->join('sh_accessory c','b.accessory_id=c.accessory_id')->where('b.goods_id',$v['goods_id'])->select();
        }

        //所有图片
        $imgData = $GoodsimgDb->alias('a')->join('sh_img i','i.img_id=a.img_id')->where('a.goods_id','in',$goods_ids)->column('img_url');

        $redData = [
            'specificationThis'=>$specificationThis,
            'specificationName'=>$specificationName,
            'specificationValue'=>$specificationValue,
            'goodsData'=>$rGoodsData,
            'imgData' => $imgData,
            'desc' => $desc
        ];
        return $redData;
    }
    /**
     * 单获取商品价格
     * $goods_id 商品id
     * $client_id 客户id
     * $unit_level 单位等级（0最小单位，1副单位1,2副单位2）
     * $num   起订量
     */
    public function goodsPrice($goods_id,$client_id,$unit_level,$num){

        $where = [];
        //单个商品
        $GoodsUnits = new GoodsUnits();
        $GoodsUnitsDb = $GoodsUnits->GoodsUnitsDb();
        //判断是否有客户独立价格
        $GoodsClientPrice = new GoodsClientPrice();
        $GoodsClientPriceDb = $GoodsClientPrice->GoodsClientPriceDb();
        $where['client_id'] = $client_id;
        $where['goods_id'] =  $goods_id;
        $ClientGoodsPriceData = $this->getClientGoodsPrice($client_id,$goods_id);
        $GoodsUnitData = $GoodsUnitsDb->where('goods_id',$goods_id)->find();
        //客户字段转换
        //单位字段转换
        //等级字段装换
        $s = '';
        $s2 = '';
        $s3 = '';
        switch ($unit_level){
            case 0:
                $s = 'client_price1';
                $s2 = 'initial_unit_price';
                $s3 = 'level_price1';
                break;
            case 1:
                $s = 'client_price2';
                $s2 = 'extra1_unit_price';
                $s3= 'level_price2';
                break;
            case 2:
                $s = 'client_price3';
                $s2 = 'extra2_unit_price';
                $s3 = 'level_price3';
                break;
        }
        //默认价格
        $GoodsUnits = new GoodsUnits();
        $GoodsUnitsDb = $GoodsUnits->GoodsUnitsDb();
        $dP = $GoodsUnitsDb->where('goods_id',$goods_id)->value($s2);
        $retP = 0;
        if($ClientGoodsPriceData!=0){//you客户

            //判断是否可购
            if($ClientGoodsPriceData['client_purchase']==0){//允许

                //判断是否达到起订要求
                if($ClientGoodsPriceData['client_num']>=$num){//满足
                    $retP = $ClientGoodsPriceData[$s];
                }else{//不满足
                    $retP = $dP;
                }
            }else{//不允许
                $retP = $dP;
            }

        }else{//wu客户

            $Client = new Client();
            $client_id = $Client->where('client_id',$client_id)->value('level_id');
            //查询等级是否you
            $GoodsLevelPrice = new GoodsLevelPrice();
            $GoodsLevelPriceDb = $GoodsLevelPrice->GoodsLevelPriceDb();
            $GoodsLevelPriceData = $GoodsLevelPriceDb->where('level_id',$client_id)->where('goods_id',$goods_id)->find();
            if($GoodsLevelPriceData){//you
                //判断是否可购
                if($GoodsLevelPriceData['level_purchase']==0){//允许
                    //判断起订量

                    if($ClientGoodsPriceData['client_num']>=$num){//满足
                        $retP = $GoodsLevelPriceData[$s3];
                    }else{//不满足
                        $retP = $dP;

                    }
                }else{//不允许
                    $retP = $dP;
                }

            }
        }
        return $retP;
    }

    //查询是否有指定客户可购
    public function getClientGoodsPrice($client_id,$goods_id){
        $GoodsClientPrice = new GoodsClientPrice();
        $GoodsClientPriceDb = $GoodsClientPrice->GoodsClientPriceDb();
        $where['client_id'] = $client_id;
        $where['goods_id'] = $goods_id;
        $data = $GoodsClientPriceDb->where($where)->find();

        if (empty($data)){
            return 0;
        }else{
            return $data;
        }

    }
    /**
     * 商品详情
     */

    /**
     * 商品详情后期处理
     */
    public function infoAfter()
    {
        $count = count($this->skus);
        for ($i = 0; $i < $count; $i++) {
            $currentSku = $this->skus[$i];

            // 商品信息不全 使用默认规格的信息
            if ($this->sku_default === $currentSku->sku_id) {
                $this->defaultSku = $currentSku;
                empty($this->goods_images) && $this->goods_images = $currentSku->sku_images;
                empty($this->price) && $this->price = $currentSku->price;
            }

            // 当前规格没有信息 使用商品信息
            empty($currentSku->sku_name) && $currentSku->sku_name = $this->goods_name;
            empty($currentSku->sku_images) && $currentSku->sku_images = $this->goods_images;
            $currentSku->defaultImage = $currentSku->sku_images[0];
            empty($currentSku->price) && $currentSku->price = $this->price;
        }

        // 第一张图作为默认图片
        $this->defaultImage = $this->goods_images[0];

        $this->doWithSpecs();

        return $this;
    }

    public function doWithSpecs()
    {
        $specsValues = [];
        $specsValuesIds = [];
        $count = count($this->specs);
        for ($i = 0; $i < $count; $i++) {
            $currentSpec = $this->specs[$i];
            // array_column($currentSpec->values, 'value_id')
            $currentSpec->valuesIds = array_map(function($value) {
                return $value->value_id;
            }, $currentSpec->values);
            $specsValues[] = $currentSpec->valuesIds;
            $specsValuesIds = array_merge($specsValuesIds, $currentSpec->valuesIds);
        }
        $this->specsValues = $specsValues;
        $this->specsValuesIds = $specsValuesIds;

        $count = count($this->skus);
        for ($i = 0; $i < $count; $i++) {
            $currentSku = $this->skus[$i];
            $currentSku->specsArray = array_values($currentSku->specs);
        }

        return $this;
    }

    //商品列表
    public function goodsList($params){
        $where = [];
        $where['is_delete'] = 0;
        $where['goods_state'] = 1;
        $request = request();
        $client_id = $request->header('company');
        //$client_id=6;
        if(!empty($params['query'])){
            $where['goods_name | goods_sn | keywords'] = ['like','%'.$params['query'].'%'];
        }
        if(!empty($params['cate_id'])){
            $where['cate_id'] = $params['cate_id'];
        }
        if($this->boolFormatInt($params['is_new'])){
            $where['is_new'] = 1;
        }
        if($this->boolFormatInt($params['is_hot'])){
            $where['is_hot'] = 1;
        }
        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 20;
        $order = '';
        if(!empty($params['sort'])){
            $order = $params['sort'];
            if($this->boolFormatInt($params['desc'])){
                $order .= ' desc';
            }else{
                $order .= ' asc';
            }
        }

        $goods = $this->where($where)->order($order)->page($page,$pageSize)->group('specification_id')->field('goods_id,goods_name,goods_img,cost_price,specification_id,specification1_name,specification2_name,specification3_name')->select();

        foreach ($goods as $k=>$v){
            $goods[$k]['units'] = $this->specificationUnits($v['specification_id'],$client_id);
        }
        $total = $this->where($where)->order($order)->group('specification_id')->field('specification_id')->count();

        $pager = [
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $total
        ];

        foreach ($goods as &$v) {
            $v['specification1_value'] = $this->where('specification_id',$v['specification_id'])->distinct(true)->column('specification1_value');
            $v['specification2_value'] = $this->where('specification_id',$v['specification_id'])->distinct(true)->column('specification2_value');
            $v['specification3_value'] = $this->where('specification_id',$v['specification_id'])->distinct(true)->column('specification3_value');
        }
        $units=[];
        return [
            'data' => $goods,

            'pager' => $pager
        ];
    }
    //
    //布尔值转化数字
    public function boolFormatInt($bool){
        return $bool == 'true' ? 1 : 0;
    }

    //数字转化布尔值
    public function intFormatBool($int){
        return $int ? true : false;
    }
    /**
     * 通过$specification_id
     * client_id 获取商品单位规格及价格
     */
    public function  specificationUnits($specification_id,$client_id){
        $GoodsDb = $this->GoodsDb();
        $where['is_delete'] = 0;
        $where['goods_state'] = 1;
        $where['specification_id'] = $specification_id;
        $data = $GoodsDb->alias('g')->
        join('sh_goods_units u','g.goods_id = u.goods_id')->
        where($where)->select();
        $ClientModel = new Client();
        $clientDb = $ClientModel->ClientDb();
        $GoodsUnitModel = new GoodsUnits();
        $GoodsUnitsDb = $GoodsUnitModel->GoodsUnitsDb();
        $GoodsUnitsModel = new Unit();
        $Units =  $GoodsUnitsModel->where('is_delete',0)->column('unit_name','unit_id');
        $level_id = $clientDb->where('client_id',$client_id)->value('level_id');
        $GoodsLevelPriceModel =  new GoodsLevelPrice();
        $GoodsLevelPriceDb = $GoodsLevelPriceModel->GoodsLevelPriceDb();
        $retData = [];
        foreach ($data as $k=>$v){
            //查询是否有指定客户可购
            $i=0;
            $j=0;
            $ClientGoodsPriceData = $this->getClientGoodsPrice($client_id,$v['goods_id']);
            $Unit = $GoodsUnitsDb->where('goods_id',$v['goods_id'])->find();
            $retData[$k]['goods_id'] = $v['goods_id'];
            $retData[$k]['guige1'] = $v['specification1_value'];
            $retData[$k]['guige2'] = $v['specification2_value'];
            $retData[$k]['guige3'] = $v['specification3_value'];
            $_d[0] = $Unit['is_use_initial_unit'];
            $_d[1]= $v['is_units'] && $Unit['is_use_extra1_unit'] ? $Unit['is_use_extra1_unit'] : 0;
            $_d[2] = $v['is_units'] && $Unit['is_use_extra2_unit'] ? $Unit['is_use_extra2_unit'] : 0;
            $retData[$k]['units'][$i]['id']=$Unit['initial_unit_id'];
            $retData[$k]['units'][$i]['name']=$Units[$Unit['initial_unit_id']];
            if($_d[1])
            {   $i++;
                $retData[$k]['units'][$i]['id']=$Unit['extra1_unit_id'];
                $retData[$k]['units'][$i]['name']=$Units[$Unit['extra1_unit_id']];
            }
            if($_d[2]){
                $i++;
                $retData[$k]['units'][$i]['id']=$Unit['extra2_unit_id'];
                $retData[$k]['units'][$i]['name']=$Units[$Unit['extra2_unit_id']];
            }
            if($ClientGoodsPriceData!=0){
                    $retData[$k]['units'][$j]['price'] =$ClientGoodsPriceData['client_price1'];
                if($_d[1]){
                    $j++;
                    $retData[$k]['units'][$j]['price']=$ClientGoodsPriceData['client_price2'];
                }
                if($_d[2]){
                    $j++;
                    $retData[$k]['units'][$j]['price']=$ClientGoodsPriceData['client_price3'];
                }

            }else{
                $GoodsLevelPrice = $GoodsLevelPriceDb->where('goods_id',$v['goods_id'])->where('level_id',$level_id)->field('level_price1,level_price2,level_price3')->find();
                if($GoodsLevelPrice){
                    $retData[$k]['units'][$j]['price'] =$GoodsLevelPrice['level_price1'];
                    if($_d[1]) {
                        $j++;
                        $retData[$k]['units'][$j]['price']=$GoodsLevelPrice['level_price2'];
                    }
                    if($_d[2]){
                        $j++;
                        $retData[$k]['units'][$j]['price']=$GoodsLevelPrice['level_price3'];
                    }

                }else{
                    $retData[$k]['units'][$j]['price'] =$Unit['initial_unit_price'];
                    if($_d[1]){
                        $j++;
                        $retData[$k]['units'][$j]['price']=$Unit['extra1_unit_price'];
                    }
                    if($_d[2]){
                        $j++;
                        $retData[$k]['units'][$j]['price']=$Unit['extra2_unit_price'];
                    }
                }
            }
        }
        return $retData;
    }
    /**
     * 通过goods_id unit_id client_id 获取商品价格及其他数据
     */
    public function gIdAndUnitPrice($goods_id,$unit_id,$client_id){
        $GoodsDb = $this->GoodsDb();
        $where['g.goods_id'] = $goods_id;
        $data = $GoodsDb->alias('g')->
        join('sh_goods_units u','g.goods_id = u.goods_id')->
        where($where)->field('g.goods_id,g.keywords,g.goods_inventory,g.goods_img,g.goods_sn,g.goods_name,g.specification1_name,g.specification2_name,g.specification3_name,g.specification1_value,g.specification2_value,g.specification3_value')->find();
        $data['unit_id'] = $unit_id;
        $GoodsUnitsModel = new Unit();
        $data['unit_name'] = $GoodsUnitsModel->where('unit_id',$unit_id)->value('unit_name');
        $ClientModel = new Client();
        $clientDb = $ClientModel->ClientDb();
        $GoodsUnitModel = new GoodsUnits();
        $ClientGoodsPriceData = $this->getClientGoodsPrice($client_id,$data['goods_id']);
        $GoodsUnitsDb = $GoodsUnitModel->GoodsUnitsDb();
        $Unit = $GoodsUnitsDb->where('goods_id',$data['goods_id'])->find();
        $level_id = $clientDb->where('client_id',$client_id)->value('level_id');
        $GoodsLevelPriceModel =  new GoodsLevelPrice();
        $GoodsLevelPriceDb = $GoodsLevelPriceModel->GoodsLevelPriceDb();
        $unit = [];
        //判断是否有客户价格
        if($ClientGoodsPriceData!=0){
            $unit[$Unit['initial_unit_id']] =$ClientGoodsPriceData['client_price1'];
            $unit[$Unit['extra1_unit_id']] =$ClientGoodsPriceData['client_price2'];
            $unit[$Unit['extra2_unit_id']] =$ClientGoodsPriceData['client_price3'];
        }else{
            $GoodsLevelPrice = $GoodsLevelPriceDb->where('goods_id',$data['goods_id'])->where('level_id',$level_id)->field('level_price1,level_price2,level_price3')->find();
            //判断是否有等级价格
            if($GoodsLevelPrice){
                $unit[$Unit['initial_unit_id']] = $GoodsLevelPrice['level_price1'];
                $unit[$Unit['extra1_unit_id']] = $GoodsLevelPrice['level_price2'];
                $unit[$Unit['extra2_unit_id']] = $GoodsLevelPrice['level_price3'];
             }else{//如果都没有就使用单位默认价格
                $unit[$Unit['initial_unit_id']] =$Unit['initial_unit_price'];
                $unit[$Unit['extra1_unit_id']]=$Unit['extra1_unit_price'];
                $unit[$Unit['extra2_unit_id']]=$Unit['extra2_unit_price'];
             }
        }

        $data['price'] = $unit[$unit_id];
        return $data;
    }

}